﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using ISS.CaseStudy.BLL;
using ISS.CaseStudy.Entities;

namespace CaseStudy.AdminPortal
{
    public partial class LoginInfo : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                HttpCookie cookie = Request.Cookies["cnuser"];
                if (cookie != null && cookie.Values["UserId"] != null)
                {
                    string id = cookie.Values["UserId"];
                    UserInfo userInfo = UserInformationBLL.GetInfo(id);
                    lblLoginUser.Text = userInfo.NickName;
                }

                if (IsLogin())
                {
                    btnLogOff.Visible = true;
                }
                else
                {
                    btnLogOff.Visible = false;
                }
            }
        }

        public bool IsLogin()
        {
            HttpCookie cookie = Request.Cookies["cnuser"];
            if (cookie != null && cookie.Values["UserId"] != null)
            {
                return true;
            }
            else 
            {
                return false;
            }
        }

        public void Login()
        {
            if (!IsLogin())
            {
                Response.Redirect("Default.aspx");
                return;
            }
        }

        public void Refresh()
        {
            HttpCookie cookie = Request.Cookies["cnuser"];
            if (cookie != null && cookie.Values["UserId"] != null)
            {
                string id = cookie.Values["UserId"];
                UserInfo userInfo = UserInformationBLL.GetInfo(id);
                lblLoginUser.Text = userInfo.NickName;
                btnLogOff.Visible = true;
            }
            else
            {
                lblLoginUser.Text = "请登录";
                btnLogOff.Visible = false;
            }
        }

        protected void btnLogOff_Click(object sender, EventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["cnuser"];
                cookie.Values.Clear();

                HttpCookie newCookie = new HttpCookie("cnuser");
                newCookie.Expires = DateTime.Now.AddHours(-2);
                Response.Cookies.Add(newCookie);
            }
            catch
            {
            }

            Refresh();

            Response.Redirect("default.aspx");
        }
    }
}